package handler;

import Util.JdbcUtil;
import pojo.InventoryInfo;
import pojo.Transaction;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class ImportDataHandler {

    public static int insertInventoryInfo(List<InventoryInfo> list) {
        int rowsAffected = 0;

        String sql = "INSERT INTO inventoryinfo (PartNumber, PartName, InventoryQuantity, CriticalValue) " +
                "VALUES (?, ?, ?, ?) " +
                "ON DUPLICATE KEY UPDATE PartName = VALUES(PartName), " +
                "InventoryQuantity = VALUES(InventoryQuantity), " +
                "CriticalValue = VALUES(CriticalValue)";

        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            for (InventoryInfo inventory : list) {
                ps.setString(1, inventory.getPartNumber());
                ps.setString(2, inventory.getPartName());
                ps.setInt(3, inventory.getInventoryQuantity());
                ps.setInt(4, inventory.getCriticalValue());
                rowsAffected += ps.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rowsAffected;
    }


    public static int insertTransaction(List<Transaction> list) {
        int rowsAffected = 0;

        String sql = "INSERT INTO transaction (TransactionNumber, PartNumber, TransactionType, Quantity, UpdateStatus) " +
                "VALUES (?, ?, ?, ?, ?) " +
                "ON DUPLICATE KEY UPDATE PartNumber = VALUES(PartNumber), " +
                "TransactionType = VALUES(TransactionType), " +
                "Quantity = VALUES(Quantity), " +
                "UpdateStatus = VALUES(UpdateStatus)";

        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            for (Transaction transaction : list) {
                ps.setString(1, transaction.getTransactionNumber());
                ps.setString(2, transaction.getPartNumber());
                ps.setString(3, transaction.getTransactionType());
                ps.setInt(4, transaction.getQuantity());
                ps.setBoolean(5, transaction.isUpdateStatus());
                rowsAffected += ps.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rowsAffected;
    }

}

